package com.majorty.mb.util;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;
import java.io.StringWriter;
/**
 * @author zhangshuai
 * @date 2019-09-23 10:54
 */
public class JsonTool {

    /**
     * 对象转JSON(默认去除掉空数据的属性)
     * @param data
     * @return json string
     */
    public static String dataToJson(Object data) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(Include.NON_NULL);
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            StringWriter sw = new StringWriter();
            mapper.writeValue(sw,data);
            return sw.toString();
        } catch (IOException e){
            e.printStackTrace();
            throw new RuntimeException("IOException from a StringWriter?");
        }
    }

    /**
     * 对象转JSON(保留所有属性)
     *
     * @param  data
     * @return json string
     */
    public static String dataToJsonWithNull(Object data) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            StringWriter sw = new StringWriter();
            mapper.writeValue(sw,data);
            return sw.toString();
        } catch (IOException e) {
            throw new RuntimeException("IOException from a StringWriter?");
        }
    }
}
